using System;
using System.Collections;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using System.IO;
using log4net;

namespace Velocity4Net.Runtime.Logging
{

    /**
     * Implementation of a simple log4j system that will either latch onto
     * an existing category, or just do a simple rolling file log.
     *
     * @author <a href="mailto:geirm@apache.org>Geir Magnusson Jr.</a>
     * @author <a href="mailto:dlr@finemaltcoding.com>Daniel L. Rall</a>
     * @author <a href="mailto:nbubna@apache.org>Nathan Bubna</a>
     * @version $Id: Log4JLogChute.java 730039 2008-12-30 03:53:19Z byron $
     * @since Velocity 1.5
     * @since 1.5
     */
    public class Log4JLogChute : LogChute
    {
        public const String RUNTIME_LOG_LOG4J_LOGGER =
                "runtime.log.logsystem.log4j.logger";
        public const String RUNTIME_LOG_LOG4J_LOGGER_LEVEL =
                "runtime.log.logsystem.log4j.logger.level";

        private RuntimeServices rsvc = null;
        private RollingFileAppender appender = null;

        /**
         * <a href="http://jakarta.apache.org/log4j/">Log4J</a> logging API.
         */
        protected ILog logger = null;

        /**
         * @see org.apache.velocity.runtime.log.LogChute#init(org.apache.velocity.runtime.RuntimeServices)
         */
        public void init(RuntimeServices rs)
        {
            rsvc = rs;

            /* first see if there is a category specified and just use that - it allows
             * the application to make us use an existing logger
             */
            String name = (String)rsvc.getProperty(RUNTIME_LOG_LOG4J_LOGGER);
            if (name != null)
            {
                logger = log4net.LogManager.GetLogger(name);
                log(LogConstants.DEBUG_ID, "Log4JLogChute using logger '" + name + '\'');
            }
            else
            {
                // create a logger with this class name to avoid conflicts
                logger = log4net.LogManager.GetLogger(this.GetType());

                // if we have a file property, then create a separate
                // rolling file log for velocity messages only
                String file = rsvc.GetString(RuntimeConstants.RUNTIME_LOG);
                if (file != null && file.Length > 0)
                {
                    initAppender(file);
                }
            }

            /* get and set specified level for this logger */
            //String lvl = rsvc.getString(RUNTIME_LOG_LOG4J_LOGGER_LEVEL);
            //if (lvl != null)
            //{
            //    log4net.LogManager
            //    Level level = Level.Debug;
            //    logger.setLevel(level);
            //}

            /* Ok, now let's see if this version of log4j supports the trace level. */
            //try
            //{
            //    Field traceLevel = typeof(Level).getField("TRACE");
            //    // we'll never get here in pre 1.2.12 log4j
            //    hasTrace = true;
            //}
            //catch (NoSuchFieldException e)
            //{
            //    log(LogConstants.DEBUG_ID,
            //        "The version of log4j being used does not support the \"trace\" level.");
            //}
        }

        // This tries to create a file appender for the specified file name.
        private void initAppender(String file)
        {
            try
            {
                // to add the appender
                PatternLayout layout = new PatternLayout("%d - %m%n");
                this.appender = new RollingFileAppender();
                appender.File = file;
                appender.Layout = layout;
                appender.AppendToFile = true;

                // if we successfully created the file appender,
                // configure it and set the logger to use only it
                appender.MaxSizeRollBackups = 1;
                appender.MaximumFileSize = "100000";

                // don't inherit appenders from higher in the logger heirarchy
                //logger.Additivity=(false);
                //logger.AddAppender(appender);
                log(LogConstants.DEBUG_ID, "Log4JLogChute initialized using file '" + file + '\'');
            }
            catch (IOException ioe)
            {
                rsvc.getLog().error("Could not create file appender '" + file + '\'', ioe);
                // throw ExceptionUtils.createRuntimeException("Error configuring Log4JLogChute : ", ioe);
                throw;
            }
        }

        /**
         *  logs messages
         *
         *  @param level severity level
         *  @param message complete error message
         */
        public void log(int level, String message)
        {
            switch (level)
            {
                case LogConstants.WARN_ID:
                    logger.Warn(message);
                    break;
                case LogConstants.INFO_ID:
                    logger.Info(message);
                    break;
                case LogConstants.TRACE_ID:

                    logger.Debug(message);
                    break;
                case LogConstants.ERROR_ID:
                    logger.Error(message);
                    break;
                case LogConstants.DEBUG_ID:
                default:
                    logger.Debug(message);
                    break;
            }
        }

        /**
         * @see org.apache.velocity.runtime.log.LogChute#log(int, java.lang.String, java.lang.Throwable)
         */
        public void log(int level, String message, System.Exception t)
        {
            switch (level)
            {
                case LogConstants.WARN_ID:
                    logger.Warn(message, t);
                    break;
                case LogConstants.INFO_ID:
                    logger.Info(message, t);
                    break;
                case LogConstants.TRACE_ID:
                    logger.Debug(message, t);
                    break;
                case LogConstants.ERROR_ID:
                    logger.Error(message, t);
                    break;
                case LogConstants.DEBUG_ID:
                default:
                    logger.Debug(message, t);
                    break;
            }
        }

        /**
         * @see org.apache.velocity.runtime.log.LogChute#isLevelEnabled(int)
         */
        public bool isLevelEnabled(int level)
        {
            switch (level)
            {
                case LogConstants.DEBUG_ID:
                    return logger.IsDebugEnabled;
                case LogConstants.INFO_ID:
                    return logger.IsInfoEnabled;
                case LogConstants.TRACE_ID:

                    return logger.IsDebugEnabled;
                //case LogConstants.WARN_ID:
                //    return logger.IsEnabledFor(Level.WARN);
                //case LogConstants.ERROR_ID:
                //    // can't be disabled in log4j
                //    return logger.IsEnabledFor(Level.ERROR);
                default:
                    return true;
            }
        }

        /**
         * Also do a shutdown if the object is destroy()'d.
         * @throws Throwable
         */
        protected void finalize()
        {
            shutdown();
        }

        /** Close all destinations*/
        public void shutdown()
        {
            if (appender != null)
            {
                //logger.RemoveAppender(appender);
                appender.Close();
                appender = null;
            }
        }

    }
}